package com.he.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.he.util.JwtUtils;
import com.he.util.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 定义一个拦截器，用来处理token问题
 * @author 布衣
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${token.key}")
    private String token;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//        //token
//        String header = request.getHeader(token);
////        System.out.println(token);
////        System.out.println(header);
//        // 如果没有token，返回错误信息
//        if (header == null || header.isEmpty()) {
//            returnJson(response, R.failure("缺少token"));
//            return false;
//        }
//
//        if (!JwtUtils.validateToken(header)) {
//            returnJson(response, R.failure("令牌失效"));
//            return false;
//        }
        return true;
    }


    /**
     * 返回JSON格式的响应信息
     *
     * @param response HttpServletResponse对象
     * @param r        响应结果
     * @throws IOException IO异常
     */
    private void returnJson(HttpServletResponse response, R r) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSONObject.toJSONString(r));
        writer.close();
    }

}
